package com.veeder.datacollection.rs232.comm;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;

import com.veeder.datacollection.exception.TimeoutException;

public abstract class Connection {
	
	protected InputStream in;
	protected OutputStream out;
	protected final Logger logger;

	// unit:seconds
	private int connectionTimeout;
	private int readTimeout;
	
	public Connection(int connectionTimeout, int readTimeout){
		this.connectionTimeout=connectionTimeout;
		this.readTimeout=readTimeout;
		this.logger = Logger.getLogger(this.getClass().getName());
		logger.setUseParentHandlers(true);
	}

	public abstract void openConnection() throws TimeoutException, IOException;

	public abstract void closeConnection();
	
	public abstract boolean isValid();

	public abstract int read(byte[] b) throws TimeoutException, IOException;
	
	public void write(byte[] b) throws IOException {
		out.write(b);
	}

	public void flush() throws IOException {
		out.flush();
	}

   public void writeWithFlushing(byte[] b) throws IOException
   {
      synchronized (out)
      {
         out.write(b);
         out.flush();
      }
   }

	public int getConnectionTimeout() {
		return this.connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public int getReadTimeout() {
		return this.readTimeout;
	}

	public void setReadTimeout(int readTimeout) {
		this.readTimeout = readTimeout;
	}

}
